from smartcab.data import db
from .blueprint import user_bp
from smartcab import login_manager
from smartcab.data.user import User

from flask import request
from flask_login import current_user, login_required, logout_user, login_user


@user_bp.route("/login", methods=["GET", "POST"])
def login():
    try:
        login, password, remember = (
            request.args["login"],
            request.args["password"],
            bool(int(request.args["remember"])),
        )
    except Exception:
        return {"status": "error", "error": "bad_request"}

    if current_user.is_authenticated:
        return {"status": "error", "error": "already_authorized"}

    with db.session() as db_sess:
        user = db_sess.query(User).filter_by(login=login).first()

        if user and user.check_password(password):
            login_user(user, remember=remember)
        else:
            return {"status": "error", "error": "unknown_user"}

    return {"status": "success"}


@user_bp.route("/logout")
@login_required
def logout():
    logout_user()
    return {"status": "success"}


@login_manager.user_loader
def load_user(user_id):
    with db.session() as db_sess:
        if user_id is not None:
            return db_sess.query(User).get(user_id)


@login_manager.unauthorized_handler
def unauthorized():
    return {"status": "error", "error": "unauthorized"}
